//
//  NewsViewController.m
//  CPU_Utility
//
//  Created by leonardo on 15/10/21.
//  Copyright © 2015年 leonardo. All rights reserved.
//

#import "NewsViewController.h"
#import <AFNetworking.h>
#import <MJExtension.h>
#import <MJRefresh.h>
#import <KVNProgress.h>
#import "NewsTableViewCell.h"
#import "NewsSearchTermsModel.h"
#import "NewsSearchResultModel.h"
#import "Util.h"
#import "ANBlurredTableView.h"
#import "NewsDetailViewController.h"

@interface NewsViewController ()<UITableViewDelegate,UITableViewDataSource>{
    NewsSearchResultModel * _newsSearchResultModel;
    NewsSearchTermsModel * _newsSearchTermsModel;
    UITableView * _tableView ;
}

@end

@implementation NewsViewController
- (instancetype)init
{
    self = [super init];
    if (self) {
        _newsSearchTermsModel = [NewsSearchTermsModel new];
       
    }
    return self;
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self CreateUI];
    [self loadData];
   
}
-(void)viewWillAppear:(BOOL)animated{
    
}
-(void)viewDidAppear:(BOOL)animated{
    
}
#pragma mark 加载数据
-(void)loadData{
    
    _newsSearchTermsModel.title = @"处理器";
    AFHTTPRequestOperationManager * manager = [Util getAFNetworkingManager];
    
    [manager.requestSerializer setValue:@"07a46715a62d81dc0ccc6c8f4689ff83" forHTTPHeaderField:@"apikey"];
    [KVNProgress showWithStatus:@"加载中..."];
    [manager GET:NEWS_API parameters:[_newsSearchTermsModel keyValues] success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
//        NSLog(@"%@",responseObject);
        _newsSearchResultModel = [NewsSearchResultModel objectWithKeyValues:responseObject[@"showapi_res_body"][@"pagebean"]];
        [_tableView reloadData];
        [_tableView.header endRefreshing];
        [KVNProgress dismiss];
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@",error.userInfo[@"NSLocalizedDescription"]);
        if ([_newsSearchTermsModel.Pages intValue]==1) {
            [_tableView.header endRefreshing];
            [KVNProgress showErrorWithStatus:error.userInfo[@"NSLocalizedDescription"] completion:nil];
        }
        else{
             [_tableView.footer setState:MJRefreshStateError];
            [KVNProgress showErrorWithStatus:error.userInfo[@"NSLocalizedDescription"] completion:nil];
        }
        
       
    }];

    
    
}

#pragma 创建UI
-(void)CreateUI{
    //navi
    self.navigationController.navigationBar.translucent = NO;
    //tabbar
    self.tabBarController.tabBar.translucent = NO;
    //TableView
    NSLog(@"%f,%f",SCREEN_WIDTH, SCREEN_HEIGHT);
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STATUSBAR_HEIGHT  - NAVI_HEIGHT - TABBAR_HEIGHT)];
    _tableView.rowHeight = 120.0f;
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(ResetData)];
    _tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(RefreshData)];
    [self.view addSubview:_tableView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarOrientationChange:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}

#pragma mark 重置数据
-(void)ResetData{//刷新数据
    _newsSearchTermsModel.Pages = @1;//[NSNumber numberWithInt:1];
    _newsSearchResultModel = nil;
    [self loadData];
    [_tableView reloadData];
    
}

#pragma mark 刷新新数据
-(void)RefreshData{//刷新新数据
        int i =  [_newsSearchTermsModel.Pages intValue] ;

    if ([_newsSearchResultModel.allPages intValue] >= (i + 1)) {
        _newsSearchTermsModel.Pages = [NSNumber numberWithInt:i ++];
        [_tableView reloadData];
    }
    else{
        [_tableView.footer setState:MJRefreshStateNoMoreData];
    }
}
#pragma mark _tableViewDataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _newsSearchResultModel.contentlist.count;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * cellID = @"cell";
    NewsTableViewCell * cell = [_tableView dequeueReusableCellWithIdentifier:cellID];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"NewsTableViewCell" owner:self options:nil] lastObject];
    }
    [cell configWith:_newsSearchResultModel.contentlist[indexPath.row]];
    
    return cell;
}

#pragma mark _tableviewDelegate
//单击单元格
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NewsDetailViewController * vc = [NewsDetailViewController new];
    vc.contentModel = _newsSearchResultModel.contentlist[indexPath.row];
    vc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}




#pragma mark 转屏通知回调
- (void)statusBarOrientationChange:(NSNotification *)notification
{
    
//    UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
//    if (orientation == UIInterfaceOrientationLandscapeRight) // home键靠右
//    {
//        [_tableView reloadData];
//    }
//    
//    if (
//        orientation ==UIInterfaceOrientationLandscapeLeft) // home键靠左
//    {
//        [_tableView reloadData];
//    }
//    
//    if (orientation == UIInterfaceOrientationPortrait)
//    {
//        [_tableView reloadData];
//    }
//    
//    if (orientation == UIInterfaceOrientationPortraitUpsideDown)
//    {
//        [_tableView reloadData];
//    }
    
    NSLog(@"%f,%f",self.view.bounds.size.height,self.view.bounds.size.width);
    _tableView.frame =CGRectInset(self.view.bounds, 2, 2);
    //[_tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
